package cn.edu.flink.scala.tutorial.watermark

import cn.edu.flink.scala.tutorial.source.{ClickSource, Event}
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.scala.function.ProcessWindowFunction
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.api.windowing.windows.TimeWindow
import org.apache.flink.util.Collector

object WatermarkTest {
  def main(args: Array[String]): Unit = {
    val env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI()
    env.setParallelism(1)

    val eventDS = env.addSource(new ClickSource)
      .assignAscendingTimestamps(_.timestamp)  // WatermarkStrategy.forMonotonousTimestamps() 的替代

    eventDS
      .keyBy(_.user)
      .window(TumblingEventTimeWindows.of(Time.seconds(10)))
      .process(new WatermarkWindowResult)
      .print()

    env.execute("WatermarkTest")
  }

  class WatermarkWindowResult extends ProcessWindowFunction[Event, String, String, TimeWindow] {
    override def process(user: String, context: Context, elements: Iterable[Event], out: Collector[String]): Unit = {
      // 提取信息
      val start = context.window.getStart
      val end = context.window.getEnd
      val count = elements.size

      // 增加水位线信息
      val currentWatermark = context.currentWatermark

      out.collect(s"窗口 $start ~ $end , 用户 $user 的活跃度为：$count, 水位线现在位于：$currentWatermark")
    }
  }
}
